package com.sunyard.authorization.config;

import com.sunyard.authorization.service.MerchantOperatorService;
import com.sunyard.dal.entity.Staff;
import com.sunyard.dal.mapper.PopedomMapper;
import com.sunyard.dal.mapper.StaffMapper;
import com.sunyard.redisUtil.RedisUtils;
import com.sunyard.utils.TokenUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class MerchantRealm extends AuthorizingRealm {

    Logger log = LoggerFactory.getLogger(MerchantRealm.class);

    @Autowired
    private PopedomMapper popedomMapper;

    @Autowired
    private StaffMapper staffMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private MerchantOperatorService merchantOperatorService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("MerchantRealm权限验证");
        String username = TokenUtil.getAccount(principalCollection.toString());
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Staff staff = staffMapper.selectByLoginName(username);
        List<String> popedomList = getPopedom(username);
        info.addStringPermissions(popedomList);
        return info;
    }


    private List<String> getPopedom(String username) {
        Staff staff = staffMapper.selectByLoginName(username);
        String key = "popedomList:" + staff.getUserType();
        List<String> popedomList = null;
        popedomList = redisUtils.get(key, List.class);
        if (popedomList == null) {
            popedomList = popedomMapper.getMchntShiroList(String.valueOf(staff.getUserType()));
            redisUtils.set(key, popedomList);
        }
        return popedomList;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("MerchantRealm身份认证");
        CustomizedToken authentication = (CustomizedToken) authenticationToken;
        try {
            login(authentication);
        } catch (IllegalAccessException e) {
            throw new AuthenticationException(e.getMessage());
        }
        //根据需要可做其他验证及异常处理
        return new SimpleAuthenticationInfo(authentication.getPrincipal(), authentication.getPassword(), "MerchantRealm");
    }

    private boolean login(CustomizedToken authentication) throws IllegalAccessException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (null == servletRequestAttributes) {
            throw new IllegalAccessException("未能获取到信息");
        }
        HttpServletRequest request = servletRequestAttributes.getRequest();
        HttpServletResponse response = servletRequestAttributes.getResponse();
        try {
            merchantOperatorService.login(response, request,
                    authentication.getUsername(),
                    String.valueOf(authentication.getPassword()));
        } catch (Exception e) {
            throw new IllegalAccessException(e.getMessage());
        }
        return true;
    }


    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof CustomizedToken;
    }

}
